package controllers

import (
	"beeblog/models"
	"path"
	"strings"

	"github.com/astaxie/beego"
)

// TopicController 文章控制器
type TopicController struct {
	beego.Controller
}

// Add 添加文章
func (topicCtl *TopicController) Add() {
	topicCtl.TplName = "topic_add.html"
}

// View 展示文章
func (topicCtl *TopicController) View() {
	topicCtl.Data["IsLogin"] = checkAccount(topicCtl.Ctx)
	var err error
	var topic *models.Topic
	if topic, err = models.GetTopic(topicCtl.Ctx.Input.Param("0")); err != nil {
		beego.Error(err)
		topicCtl.Redirect("/", 302)
		return
	}
	topicCtl.Data["Topic"] = topic
	topicCtl.Data["Labels"] = strings.Split(topic.Labels, " ")

	if topicCtl.Data["Comments"], err = models.GetAllReplies(topicCtl.Ctx.Input.Param("0")); err != nil {
		beego.Error(err)
		// topicCtl.Redirect("/", 302)//评论获取失败后，不影响文章浏览
		return
	}
	topicCtl.TplName = "topic_view.html"
}

// Modify 修改文章
func (topicCtl *TopicController) Modify() {
	if !checkAccount(topicCtl.Ctx) {
		topicCtl.Redirect("/login", 302)
		return
	}
	topicCtl.Data["IsLogin"] = true
	var err error
	topicCtl.Data["Topic"], err = models.GetTopic(topicCtl.Input().Get("tid"))
	if err != nil {
		beego.Error(err)
		topicCtl.Redirect("/", 302)
		return
	}
	topicCtl.TplName = "topic_modify.html"
}

// Get 文章控制器的get请求处理
func (topicCtl *TopicController) Get() {
	topicCtl.Data["IsTopic"] = true
	topicCtl.Data["IsLogin"] = checkAccount(topicCtl.Ctx)

	var err error
	topicCtl.Data["Topics"], err = models.GetAllTpics("", "", false)
	if err != nil {
		beego.Error(err)
	}

	topicCtl.TplName = "topic.html"
}

//Delete 删除文章
func (topicCtl *TopicController) Delete() {
	if !checkAccount(topicCtl.Ctx) {
		topicCtl.Redirect("/login", 302)
		return
	}
	if err := models.DelTopic(topicCtl.Ctx.Input.Param("0")); err != nil {
		beego.Error(err)
		topicCtl.Redirect("/", 302)
		return
	}
	topicCtl.Redirect("/topic", 302)
}

// Post 文章控制器的post请求处理
func (topicCtl *TopicController) Post() {
	if !checkAccount(topicCtl.Ctx) {
		topicCtl.Redirect("/login", 302)
		return
	}
	//解析表单数据
	input := topicCtl.Input()
	tid := input.Get("tid")
	title := input.Get("title")
	category := input.Get("category")
	labels := input.Get("labels")
	content := input.Get("content")
	//读取上传文件
	_, fh, err := topicCtl.GetFile("attachment")
	if err != nil {
		beego.Error(err)
	}
	var attachment string
	if fh != nil {
		//保存附件
		attachment = fh.Filename
		if err = topicCtl.SaveToFile("attachment", path.Join("attachment", attachment)); err != nil {
			beego.Error(err)
		}
	}

	if len(tid) == 0 {
		err = models.AddTopic(title, category, labels, content, attachment)
	} else {
		err = models.ModifyTopic(tid, title, category, labels, content, attachment)
	}

	if err != nil {
		beego.Error(err)
	}
	topicCtl.Redirect("/topic", 302)
}
